import axios from 'axios'
import { getToken, removeToken } from '@/utils/auth.js'
import { message } from 'antd'
import history from './history'
// 环境变量的接口基地址配置
let baseUrl = ''
if (process.env.NODE_ENV === 'production') {
  baseUrl = 'http://localhost:3000/api'
} else {
  // 代理
  baseUrl = '/api'
}
// 创建axios副本
const request = axios.create({
  baseURL: baseUrl,
  timeout: 5000,
})
// 请求拦截器
request.interceptors.request.use(
  (config) => {
    const token = getToken()
    if (token !== '') {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (err) => {
    return Promise.reject(err)
  }
)
// 响应拦截器
request.interceptors.response.use(
  (res) => {
    return res.data
  },
  (err) => {
    console.log([err])
    // token超时处理
    if (err.response && err.response.status == '401') {
      message.warning('请重新登陆!')
      removeToken()
      history.push('/login')
    }
    return Promise.reject(err)
  }
)
export default request
